﻿using System;
using System.Linq;
using System.IO;
using Styx;
using Styx.Plugins;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Windows.Forms;
using Styx.WoWInternals;
using Styx.Helpers;


namespace ChatLog
{
    public class ChatLog : HBPlugin
    {
        /* 
         * This product is provided for free through www.botHaven.com, and is also available for download from botHaven.
         * Distribution of this product by anyone other than Administrators of www.botHaven.com or No1KnowsY is not allowed.
         * Uploading this product anywhere, whether credit is given or not, is not allowed.
         * 
         * Plugin Name: Chat Logger
         * Author: No1KnowsY
         * Creation Date: 14JAN2013
         * 
         * Description: Log chat events to default log file.  Each log is stored as Character-Realm (TimeStarted TimeStamp)
         * Default LogPath:  Honorbuddy/Logs/ChatLogs/[Character]-[Realm]/DateTime.OfBotStarted
         * 
         * This product was not created by those at GmbH Bossland, and no support for it will be recieved from them, unless they deem otherwise.
         * Any support, suggestions, or input can be made on the botHaven Forums: http://forums.bothaven.com/
         * 
         * Now please, enjoy!
         */

        public override string Name { get { return "Chat Logger"; } }
        public override string Author { get { return "No1KnowsY"; } }
        public override Version Version { get { return new Version(1, 1); } }
        public Styx.WoWInternals.WoWObjects.LocalPlayer Me { get { return Styx.StyxWoW.Me; } }
        public static DateTime StartTime;
        private bool _initialized = false;
        public override bool WantButton { get { return true; } }
        public override string ButtonText { get { return "Settings"; } }

        public static string LogFilePath
        {
            get { return string.Format("{0}\\ChatLogs\\{1}-{2}\\{3}.txt", Path.GetDirectoryName(Application.ExecutablePath), StyxWoW.Me.Name, Lua.GetReturnVal<string>("return GetRealmName()", 0), StartTime.ToCustomStamp()); }
        }

        public void Log(string argument)
        {
            Styx.Common.Logging.Write("[{0}] {1}", Name, argument);
        }

        #region UserInterface
        private Form _configForm;
        public override void OnButtonPress()
        {
            if (_configForm == null || _configForm.IsDisposed || _configForm.Disposing)
                _configForm = new ChatLogUI();

            _configForm.Show();
        }
        #endregion

        public override void Initialize()
        {
            if (_initialized)
                return;

            StartTime = DateTime.Now;
            ChatLogSettings.Instance.Load();

            if (!Directory.Exists(Path.GetDirectoryName(LogFilePath)))
                Directory.CreateDirectory(Path.GetDirectoryName(LogFilePath));

            Styx.CommonBot.Chat.Guild += new Styx.CommonBot.Chat.ChatMessageHandlerEx<Styx.CommonBot.Chat.ChatGuildEventArgs>(Chat_Guild);
            Styx.CommonBot.Chat.Say += new Styx.CommonBot.Chat.ChatMessageHandlerEx<Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs>(Chat_Say);
            Styx.CommonBot.Chat.Whisper += new Styx.CommonBot.Chat.ChatMessageHandlerEx<Styx.CommonBot.Chat.ChatWhisperEventArgs>(Chat_Whisper);
            Styx.CommonBot.Chat.Yell += new Styx.CommonBot.Chat.ChatMessageHandlerEx<Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs>(Chat_Yell);
            Log("Loaded v" + Version.ToString() + " (www.botHaven.com)");
            AddToLog("Plugin Started.  Events Attached.  Ready to go.");
            _initialized = true;
        }

        #region AddToLogs
        void AddToLog(string channel, string sender, string message)
        {
            if (!File.Exists(LogFilePath))
                return;

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(LogFilePath, true))
            {
                //Output example:  [Guild](4:27) Imadruid: Hi scrubs!
                //Masked example:  [Guild](4:27) I******d: Hi scrubs!
                //Output Syntax:  [Channel](Hours:Minutes) ToonName: Message
                if (!ChatLogSettings.Instance.MaskNames)
                    file.WriteLine(string.Format("({1}:{2}) [{0}] {3}: {4}", channel, DateTime.Now.Hour, DateTime.Now.Minute, sender, message));
                else
                    file.WriteLine(string.Format("({1}:{2}) [{0}] {3}: {4}", channel, DateTime.Now.Hour, DateTime.Now.Minute, sender.ToHiddenName(), message));
            }  
        }
        void AddToLog(string Message)
        {
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(LogFilePath, true))
            {
                file.WriteLine(Message);
            }  
        }
        #endregion

        #region ChannelEvents
        void Chat_Yell(Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs e)
        {
            if (!ChatLogSettings.Instance.Yell)
                return;

            Log("Recieved Yell Message.");
            AddToLog("Yell", e.Author, e.Message);
            //Output as yell
        }

        void Chat_Whisper(Styx.CommonBot.Chat.ChatWhisperEventArgs e)
        {
            if (!ChatLogSettings.Instance.Whisper)
                return;

            Log("Recieved Whisper Message.");
            AddToLog("Whisper", e.Author, e.Message);
            //Output as whisper event
        }

        void Chat_Say(Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs e)
        {
            if (!ChatLogSettings.Instance.Say)
                return;

            Log("Recieved Say Message.");
            AddToLog("Say", e.Author, e.Message);
            //Output as say event
        }

        void Chat_Guild(Styx.CommonBot.Chat.ChatGuildEventArgs e)
        {
            if (!ChatLogSettings.Instance.Guild)
                return;

            Log("Recieved Guild Message.");
            AddToLog("Guild", e.Author, e.Message);
            //Output as guild event
        }
        #endregion

        public override void Pulse()
        {
        }
    }

    //Enter Form Code under this

    //Enter Designer Under this

    //ChatLogSettings - No extra files
    public class ChatLogSettings : Settings
    {
        public static readonly ChatLogSettings Instance = new ChatLogSettings();

        public ChatLogSettings()
            : base(Path.Combine(Settings.SettingsDirectory, string.Format(@"ChatLogger\{0}-{1}.xml", StyxWoW.Me.Name, Lua.GetReturnVal<string>("return GetRealmName()", 0))))
        {
        }

        [Setting, DefaultValue(true)]
        public bool Guild { get; set; }

        [Setting, DefaultValue(true)]
        public bool Say { get; set; }

        [Setting, DefaultValue(true)]
        public bool Whisper { get; set; }

        [Setting, DefaultValue(true)]
        public bool Yell { get; set; }

        [Setting, DefaultValue(true)]
        public bool MaskNames { get; set; }
    }

    public static class Extensions
    {
        public static String ToCustomStamp(this DateTime dt)
        {
            return string.Format("{0} {1} {2} {3}-{4}-{5}", dt.DayOfWeek, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
        }

        public static String ToHiddenName(this String s)
        {
            string j = "";
            int u = s.Count() - 3;
            for (int x = 0; x < u; x++)
                j += "*";
            return string.Format(s.ToCharArray().First() + (j) + s.ToCharArray().Last());

        }
    }
}


